orderController.$inject = ['orderService','$scope'];

function orderController(orderService,$scope) {

    var vm = this;
    vm.orders=[];

    vm.uorders=[];
    vm.rorders=[];
    vm.dorders=[];
    vm.forders=[];
    vm.reorders=[];

    //broadcast receive to get untreated orders
    $scope.$on('order', function (ev, v) {

        vm.untreated();
    })

    orderService.getAllUntreatedOrder().then(function (data) {
        vm.uorders = data.data.data;
        vm.orders = vm.uorders;
        console.log(vm.orders);
    });


    orderService.getAllReceiveOrder().then(function (data) {
        vm.rorders = data.data.data;
    });


    orderService.getAllDeliveryOrder().then(function (data) {

        vm.dorders = data.data.data;
    });


    orderService.getAllFinishOrder().then(function (data) {

        vm.forders = data.data.data;
    });

    orderService.getAllRefuseOrder().then(function (data) {

        vm.reorders = data.data.data;
    });


    vm.untreated = function () {
        vm.orders = vm.uorders;
    }

    vm.receive = function () {
        vm.orders = vm.rorders;
    }

    vm.delivery = function () {
        vm.orders = vm.dorders;
    }

    vm.finish = function () {
        vm.orders = vm.forders;
    }

    vm.refuse = function () {
        vm.orders = vm.reorders;
    }


    vm.receiveOrder = function (order_id) {

        console.log("receive Order" +order_id);

        orderService.updateReceiveOrder(order_id).then(function (data) {

            console.log(data);
            removeByValue(vm.uorders,order_id);
            vm.rorders.push(data.data.data);
            vm.orders = vm.rorders;
        });
    }

    vm.refuseOrder = function (order_id) {



        orderService.updateRefuseOrder(order_id).then(function (data) {
            removeByValue(vm.uorders,order_id);
            vm.reorders.push(data.data.data);
            vm.orders = vm.reorders;
        });
    }

    vm.deliveryOrder = function (order_id) {

        orderService.updateDeliveryOrder(order_id).then(function (data) {
            removeByValue(vm.rorders,order_id);
            vm.dorders.push(data.data.data);
            vm.orders = vm.dorders;
        });
    }


    function removeByValue(arr, id) {
        for(var i=0; i<arr.length; i++) {
            if(arr[i].order_id == id) {
                arr.splice(i, 1);
                break;
            }
        }
    }

}

module.exports = orderController;

